package org.dreamwork.jasmine2.web.controls.datagrid;

import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.jasmine2.web.controls.Literal;
import org.dreamwork.jasmine2.web.controls.WebContainer;
import org.dreamwork.peony.DataBinder;
import org.dreamwork.util.StringUtil;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2010-10-14
 * Time: 15:46:37
 */
public class Caption extends WebContainer {
    private Position position = Position.Top;
    private String text;

    public Caption () {
        htmlTagName = "caption";
        viewStateEnabled = false;
    }

    @Override
    public void init () {
        super.init ();
        ((DataGrid) parent).caption = this;
    }

    public Position getPosition () {
        return position;
    }

    public void setPosition (Position position) {
        this.position = position;
    }

    @Override
    public void onDataBind (Object sender) throws EventException {
        WebContainer p = (WebContainer) parent;
        if (p == null || p.getDataSource () == null || StringUtil.isEmpty (valueField)) return;

        if (childControls.count () != 0) return;

        Object value = DataBinder.eval (p.getDataSource (), valueField);
        if (value != null) text = value.toString ();
        createChildControls (true);
    }

    private void createChildControls (boolean onDataBind) {
        if (!onDataBind)
            super.createChildControls ();
        else {
            childControls.clear ();
            this.addControl (new Literal (text));
        }
        childControlCreated = true;
    }
}